﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Vit.SchemaExplorer
{
    [Serializable]
    public class TableSchema : TabularObjectBase<TableColumnSchema>
    {
        public TableSchema()
            : base()
        {
            PrimaryKeys = new List<PrimaryKeySchema>();
            ForeignKeys = new List<ForeignKeySchema>();
        }

        private List<TableSchema> parentTables;

        public List<TableSchema> ParentTables
        {
            get
            {
                if (parentTables == null)
                {
                    parentTables = new List<TableSchema>();
                    foreach (ForeignKeySchema fk in this.ForeignKeys)
                    {
                        parentTables.Add(fk.PrimaryTable);
                    }
                }
                return parentTables;
            }
        }

        private List<TableSchema> childTables;

        public List<TableSchema> ChildTables
        {
            get
            {
                if (childTables == null)
                {
                    childTables = new List<TableSchema>();
                    foreach (TableSchema tbl in this.Schema.Tables)
                    {
                        if (tbl.ForeignKeys.Any(o => string.Equals(o.PrimaryTable.FullName, this.FullName, StringComparison.OrdinalIgnoreCase)))
                        {
                            childTables.Add(tbl);
                        }
                    }
                }
                return childTables;
            }
        }

        public List<PrimaryKeySchema> PrimaryKeys { get; set; }
        public List<ForeignKeySchema> ForeignKeys { get; set; }
    }
}
